package org.yzh.commons.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.StringUtils;
import org.yzh.commons.model.UserPrincipal;
import org.yzh.commons.model.enums.Role;

public class JWTUtil {

    private static Algorithm algorithm;
    private static JWTVerifier verifier;

    static {
        initialSecret("test");
    }

    public static void initialSecret(String secret) {
        if (StringUtils.isNotBlank(secret)) {
            algorithm = Algorithm.HMAC256(secret);
            verifier = JWT.require(algorithm).build();
        }
    }

    public static String sign(UserPrincipal user) {
        JWTCreator.Builder builder = JWT.create()
                .withClaim("i", user.getId())
                .withClaim("r", String.valueOf(user.getRole()))
                .withIssuedAt(user.getIssuedAt())
                .withExpiresAt(user.getExpiresAt());
        return builder.sign(algorithm);
    }

    public static UserPrincipal unsign(String token) {
        DecodedJWT jwt = verifier.verify(token);
        UserPrincipal user = new UserPrincipal(
                jwt.getClaim("i").asInt(),
                Role.valueOf(jwt.getClaim("r").asString()),
                jwt.getIssuedAtAsInstant(),
                jwt.getExpiresAtAsInstant());
        return user;
    }
}